<template>
    <el-upload name="file" :show-file-list="false" accept=".png,.PNG,.jpg,.JPG,.jpeg,.JPEG,.gif,.GIF,.bmp,.BMP"
               :multiple="false" :http-request="uploadImage">

        <div class="cover-upload-btn">
            <template v-if="modelValue">
                <img :src="modelValue"/>
            </template>
            <span class="iconfont icon-upload" v-else></span>
        </div>
    </el-upload>
</template>

<script setup>
    import {ref, onMounted} from 'vue';
    import axios from 'axios'

    const imageUrl = ref(''); // 初始化为空
    const props = defineProps({
        modelValue: {
            type: String, // 与你的图片 URL 类型匹配
            default: null,
        },
    });
    const jwtToken = localStorage.getItem('jwtToken');

    const axiosInstance = axios.create({
        headers: {
            'Token': jwtToken // 将JWT令牌放入请求头的token字段
        }
    });

    //上传头像文件
    const emit = defineEmits();
    const uploadImage = (file) => {
        console.log(file);
        const formData = new FormData();
        formData.append('image', file.file);

        axiosInstance.post('http://localhost:8080/upload', formData)
            .then((response) => {
                console.log(response.data);
                imageUrl.value = response.data.data;
                const filename = imageUrl.value;
                console.log(filename);
                emit("update:modelValue", filename);
                const onFilenameUpdate = (filename) => {
                    emit('update:filename', filename);
                }
                onFilenameUpdate(filename);
            })
            .catch((error) => {
                console.error('创建失败', error);
            });
    }
</script>

<style lang="scss">
    .cover-upload-btn {
        width: 150px;
        height: 150px;
        background-color: #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        /* border-radius: 100px; */

        .iconfont {
            font-size: 50px;
            color: #a8a6a6;
        }

        img {
            width: 100%;
            /* border-radius: 100px; */
        }
    }
</style>